﻿using System;
using IteraProvisioning.Core;
using OfficeDevPnP.Core.Entities;
using ProvisioningLibrary.Models;
using Microsoft.SharePoint.Client;
using System.Net.Mail;

namespace ProvisioningLibrary.Handlers
{
    public class SiteHandler : Handler
    {
        private const string AppCatalogUrl = "https://iteracloud.sharepoint.com/sites/appcatalog";
        private const string BrandingThemeName = "Itera";
        private const string ContentTypeName = "Customer Details Type";
        public Url CreateSite(SubsiteInfo subsite, CustomerDetails details)
        {
            if (CheckInfo(subsite))
            {
                using (var adminContext = GetContext(subsite.HostUrl))
                {
                    if (!adminContext.Web.WebExists(subsite.SiteName))
                    {
                        // Create new sub web according the external data or data from CRM
                        Web newWeb = adminContext.Web.CreateWeb(subsite.SiteTitle, subsite.SiteName, subsite.Description, subsite.Template, 1033, true, false);
                        adminContext.Load(newWeb, w => w.Url);
                        adminContext.ExecuteQuery();

                        DoProvision(adminContext, newWeb, details);

                        SendEmailToRequestor(newWeb.Url, subsite.Email);
                    }
                    return new Url() { HostUrl = subsite.HostUrl, SiteName = subsite.SiteName };
                }
            }
            throw new Exception("Not enough information about subsite.");
        }

        private bool CheckInfo(SubsiteInfo info)
        {
            return NotEmptyString(info.HostUrl) && NotEmptyString(info.SiteName) && NotEmptyString(info.Template) && NotEmptyString(info.SiteTitle) && NotEmptyString(info.Description);
        }

        private bool NotEmptyString(string str)
        {
            return !(String.IsNullOrEmpty(str) || String.IsNullOrWhiteSpace(str));
        }

        private void DoProvision(ClientContext adminContext, Web newWeb, CustomerDetails details)
        {
            // Activate required features
            EnsureRequiredFeaturesActive(adminContext);

            // Create columns or fields according to XML schema (Resources/IteraFields.xml)
            adminContext.Web.CreateFieldsFromXMLString(Properties.Resources.IteraFields);

            // Create content types according to XML schema (Resources/IteraContentType.xml) and link created fields to it
            adminContext.Web.CreateContentTypeFromXMLString(Properties.Resources.IteraContentType);

            // Manage App Catalog site
            AppCatalogHandler appCatHandler = new AppCatalogHandler();
            appCatHandler.ManageAppWeb(AppCatalogUrl);

            // Link created content type to list as default content type
            ContentType iteraContentType = adminContext.Web.GetContentTypeByName(ContentTypeName);
            newWeb.AddContentTypeToList("Site Pages", iteraContentType, true);

            ThemeEntity iteraTheme = adminContext.Web.GetComposedLook(BrandingThemeName);

            // Manage new web
            WebHandler webHandler = new WebHandler();
            webHandler.ManageNewWeb(newWeb.Url, iteraContentType, iteraTheme, details, appCatHandler.AppsList);
        }

        private void EnsureRequiredFeaturesActive(ClientContext adminContext)
        {
            Guid pushNotify = new Guid("41E1D4BF-B1A2-47F7-AB80-D5D6CBBA3092"); // Push notifications feature Id.
            adminContext.Web.ActivateDisabledFeature(pushNotify);
        }

        private void SendEmailToRequestor(string siteUrl, string requestorEmail)
        {
            if (!NotEmptyString(requestorEmail))
                return;

            using (MailMessage msg = new MailMessage())
            {
                msg.From = new MailAddress("sahil.malik@mail.ru");
                msg.To.Add(new MailAddress(requestorEmail));
                msg.Subject = "Your web has been created.";
                msg.Body = string.Format("Your web has been now created to {0}.", siteUrl);

                SmtpClient smtp = new SmtpClient("smtp.mail.ru", 587);                               // host
                smtp.Credentials = new System.Net.NetworkCredential("sahil.malik@mail.ru", "sharepoint2013");      // credentials
                smtp.EnableSsl = true;

                smtp.Send(msg);
            }
        }
    }
}